package com.thoughtworks.android.androsphere.service.c2dm;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;

import org.apache.log4j.Logger;

import com.thoughtworks.android.androsphere.model.CloudRequest;

import static com.thoughtworks.android.androsphere.service.GoogleServiceConstants.C2DM_COLLAPSE_KEY;
import static com.thoughtworks.android.androsphere.service.GoogleServiceConstants.C2DM_DATA_FROM;
import static com.thoughtworks.android.androsphere.service.GoogleServiceConstants.C2DM_DATA_MESG;
import static com.thoughtworks.android.androsphere.service.GoogleServiceConstants.C2DM_DELAY_WHILE_IDLE;
import static com.thoughtworks.android.androsphere.service.GoogleServiceConstants.C2DM_REGISTRATION_ID;

public class C2DMServiceImpl implements C2DMService {
    private static final Logger logger = Logger.getLogger(C2DMServiceImpl.class);

    private LinkedBlockingQueue<Map<String, String>> queue;

    public C2DMServiceImpl(C2DMServiceThread thread) {
        queue = new LinkedBlockingQueue<Map<String, String>>();
        thread.setQueue(queue);
        thread.start();
    }

    public void push(List<String> peerRegistrations, CloudRequest cloudRequest) {
        logger.debug("Sending Message Broadcast from DeviceId:" + cloudRequest.getDevice());
        for (String registrationId : peerRegistrations) {
            Map<String, String> postDataMap = createPostData(registrationId, generateCollapseKey(cloudRequest),
                cloudRequest);
            queue.add(postDataMap);
        }
    }

    private Map<String, String> createPostData(String registrationId, String collapseKey, CloudRequest cloudRequest) {
        Map<String, String> postDataMap = new HashMap<String, String>();
        postDataMap.put(C2DM_REGISTRATION_ID, registrationId);
        postDataMap.put(C2DM_DELAY_WHILE_IDLE, "1");
        postDataMap.put(C2DM_COLLAPSE_KEY, collapseKey);
        postDataMap.put(C2DM_DATA_MESG, cloudRequest.getData());
        postDataMap.put(C2DM_DATA_FROM, cloudRequest.getDevice());
        return postDataMap;
    }

    private String generateCollapseKey(CloudRequest cloudRequest) {
        return cloudRequest.getDevice() + "+" + cloudRequest.getData();
    }
}
